package org.petstore.web.servlet;

import com.alibaba.fastjson.JSON;
import org.petstore.domain.Item;
import org.petstore.domain.Product;
import org.petstore.service.CatalogService;
import org.petstore.util.Result;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

public class ShowInformationServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String categoryId = req.getParameter("categoryId");
        resp.setContentType("text/json");//以json形式输出
        PrintWriter out=resp.getWriter();
        Result result1=new Result();
        CatalogService catalogService = new CatalogService();
        List<Product> productList = catalogService.getProductListByCategory(categoryId);
        String productId=String.format("%-12s","Product ID");
        String name=String.format("%-26s","Name");
        String itemId=String.format("%-12s","Item Id");
        String response = itemId+productId+name+"\n";
        int i = 0;
        while(i < productList.size()){
            Product product = productList.get(i);
            List<Item> itemList = catalogService.getItemListByProduct(product.getProductId());
            for(int j=0;j<itemList.size();j++){
                Item item=itemList.get(j);
                productId=String.format("%-12s", product.getProductId());
                name=String.format("%-26s",product.getName());
                itemId=String.format("%-10s",item.getItemId());
                response += itemId+productId+name+"\n";;
            }
            i++;
        }
        result1.setCode(11);
        result1.setMsg(response);
        String str = JSON.toJSONString(result1);
        out.print(str);
        out.flush();
        out.close();
    }
}

